package com.example.mydy.withdraw;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.mydy.R;
import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.MockDataManager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class WithdrawActivity extends AppCompatActivity {

    private static final String TAG = "WithdrawActivity";
    public static final double MINIMUM_WITHDRAWAL = 1.0; // 最低提现金额
    private static final String PREFS_NAME = "MyAppPrefs";
    
    private ViewPager2 viewPager;
    private Button btnPrevious;
    private Button btnNext;
    private TextView tvTitle;
    private ImageButton btnBack;
    
    // 步骤指示器
    private TextView[] stepIndicators = new TextView[4];
    private View[] stepLines = new View[3];
    
    private WithdrawPagerAdapter pagerAdapter;
    private WithdrawDataManager dataManager;
    private MockDataManager mockDataManager;
    private UserInfo currentUser;
    private int currentStep = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdraw);
        
        // 初始化视图
        initViews();
        
        // 初始化数据
        initData();
        
        // 设置ViewPager
        setupViewPager();
        
        // 设置步骤指示器
        updateStepIndicators(0);
        
        // 设置点击事件
        setupListeners();
    }

    private void initViews() {
        viewPager = findViewById(R.id.view_pager);
        btnPrevious = findViewById(R.id.btn_previous);
        btnNext = findViewById(R.id.btn_next);
        tvTitle = findViewById(R.id.tv_title);
        btnBack = findViewById(R.id.btn_back);
        
        // 步骤指示器
        stepIndicators[0] = findViewById(R.id.step_indicator_1);
        stepIndicators[1] = findViewById(R.id.step_indicator_2);
        stepIndicators[2] = findViewById(R.id.step_indicator_3);
        stepIndicators[3] = findViewById(R.id.step_indicator_4);
        
        // 步骤线
        stepLines[0] = findViewById(R.id.step_line_1);
        stepLines[1] = findViewById(R.id.step_line_2);
        stepLines[2] = findViewById(R.id.step_line_3);
        
        // 添加查看提现记录按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> onBackPressed());
        
        // 添加标题右侧的提现记录按钮
        TextView tvViewHistory = new TextView(this);
        tvViewHistory.setText("提现记录");
        tvViewHistory.setTextColor(getResources().getColor(R.color.purple_500));
        tvViewHistory.setTextSize(14);
        tvViewHistory.setPadding(16, 0, 16, 0);
        
        RelativeLayout titleBar = (RelativeLayout) tvTitle.getParent();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_END);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        titleBar.addView(tvViewHistory, params);
        
        tvViewHistory.setOnClickListener(v -> {
            Intent intent = new Intent(WithdrawActivity.this, WithdrawalHistoryActivity.class);
            startActivity(intent);
        });
    }

    private void initData() {
        // 获取数据管理器
        dataManager = WithdrawDataManager.getInstance();
        dataManager.clear(); // 清除旧数据
        
        // 获取MockDataManager实例
        mockDataManager = MockDataManager.getInstance();
        
        // 获取当前用户
        currentUser = mockDataManager.getCurrentUser();
        if (currentUser == null) {
            Toast.makeText(this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 加载支付宝账户信息
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String alipayAccount = prefs.getString("alipay_account", "");
        String alipayName = prefs.getString("alipay_name", "");
        
        // 更新数据管理器
        dataManager.setAlipayAccount(alipayAccount);
        dataManager.setAlipayName(alipayName);
    }

    private void setupViewPager() {
        pagerAdapter = new WithdrawPagerAdapter(this);
        viewPager.setAdapter(pagerAdapter);
        
        // 禁用用户滑动
        viewPager.setUserInputEnabled(false);
    }

    private void setupListeners() {
        // 返回按钮
        btnBack.setOnClickListener(v -> onBackPressed());
        
        // 上一步按钮
        btnPrevious.setOnClickListener(v -> {
            navigateToPreviousStep();
        });
        
        // 下一步按钮
        btnNext.setOnClickListener(v -> {
            navigateToNextStep();
        });
    }

    private void navigateToPreviousStep() {
        if (currentStep > 0) {
            currentStep--;
            viewPager.setCurrentItem(currentStep);
            updateStepIndicators(currentStep);
            updateNavigationButtons();
        }
    }

    private void navigateToNextStep() {
        // 验证当前步骤
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag("f" + viewPager.getAdapter().getItemId(currentStep));
        
        if (currentFragment instanceof WithdrawStepListener) {
            WithdrawStepListener listener = (WithdrawStepListener) currentFragment;
            if (!listener.validate()) {
                // 如果验证失败，特别是在第3步时显示提示
                if (currentStep == 2) {
                    Toast.makeText(this, "请先阅读并同意《提现服务协议》", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
        
        // 如果是最后一步，不执行任何操作
        if (currentStep == 3) {
            return;
        }
        
        // 如果是倒数第二步，提交提现申请
        if (currentStep == 2) {
            submitWithdrawalRequest();
        }
        
        currentStep++;
        viewPager.setCurrentItem(currentStep);
        updateStepIndicators(currentStep);
        updateNavigationButtons();
    }

    private void updateStepIndicators(int position) {
        // 更新标题
        switch (position) {
            case 0:
                tvTitle.setText("设置提现金额");
                break;
            case 1:
                tvTitle.setText("确认支付宝账户");
                break;
            case 2:
                tvTitle.setText("确认提现信息");
                break;
            case 3:
                tvTitle.setText("提现申请结果");
                break;
        }
        
        // 更新步骤指示器
        for (int i = 0; i < stepIndicators.length; i++) {
            if (i < position) {
                // 已完成步骤
                stepIndicators[i].setBackgroundResource(R.drawable.step_active);
                stepIndicators[i].setTextColor(getResources().getColor(android.R.color.white));
            } else if (i == position) {
                // 当前步骤
                stepIndicators[i].setBackgroundResource(R.drawable.step_active);
                stepIndicators[i].setTextColor(getResources().getColor(android.R.color.white));
            } else {
                // 未完成步骤
                stepIndicators[i].setBackgroundResource(R.drawable.step_inactive);
                stepIndicators[i].setTextColor(getResources().getColor(android.R.color.darker_gray));
            }
        }
        
        // 更新步骤线
        for (int i = 0; i < stepLines.length; i++) {
            if (i < position) {
                // 已完成步骤线
                stepLines[i].setBackgroundResource(R.drawable.step_active);
            } else {
                // 未完成步骤线
                stepLines[i].setBackgroundResource(R.drawable.step_inactive);
            }
        }
    }

    private void updateNavigationButtons() {
        // 更新按钮状态
        if (currentStep == 0) {
            btnPrevious.setVisibility(View.GONE);
            btnNext.setText("下一步");
        } else if (currentStep == 3) {
            btnPrevious.setVisibility(View.GONE);
            btnNext.setVisibility(View.GONE);
        } else {
            btnPrevious.setVisibility(View.VISIBLE);
            btnNext.setText(currentStep == 2 ? "提交申请" : "下一步");
        }
    }

    private void submitWithdrawalRequest() {
        Log.d(TAG, "提交提现申请: 用户名=" + (currentUser != null ? currentUser.getUsername() : "null") + 
              ", 金额=" + dataManager.getWithdrawAmount() + 
              ", 支付宝账号=" + dataManager.getAlipayAccount() + 
              ", 支付宝姓名=" + dataManager.getAlipayName());
        
        // 创建提现记录
        int recordId = mockDataManager.createWithdrawalRecord(
                currentUser.getUsername(), 
                dataManager.getWithdrawAmount(), 
                dataManager.getAlipayAccount(), 
                dataManager.getAlipayName());
        
        Log.d(TAG, "提现申请结果: recordId=" + recordId);
        
        // 保存提现结果
        if (recordId > 0) {
            // 设置提现记录ID
            dataManager.setWithdrawalId(recordId);
            
            // 设置提现申请时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String currentTime = sdf.format(new Date());
            dataManager.setWithdrawalTime(currentTime);
            
            Toast.makeText(this, "提现申请已提交，等待审核", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "提现申请提交失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
} 